package com.example.scanfast.service;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;

import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.example.scanfast.MainActivity;
import com.example.scanfast.R;
import com.example.scanfast.addfile.AddFileDetailsActivity;
import com.example.scanfast.constant.Constant;

import android.app.Service;
import android.os.IBinder;

import androidx.annotation.Nullable;

import java.io.File;


public class MediaFilesObserverService extends Service {

    private static final String TAG = "MediaFilesObserver";

    private Context context;
    private ContentResolver contentResolver;
    private MediaObserver observer;

    private final String channel_id = "xulu";
    private final String channel_name = "myChannelName";
    private static final int DATABASE_QUERY_NOTIFICATION_ID = 1;
    private int importance = NotificationManagerCompat.IMPORTANCE_HIGH;

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            @SuppressLint("WrongConstant") NotificationChannel channel = new NotificationChannel("xiaoxulu", "myName", importance);
            NotificationManager notificationManager = getSystemService(NotificationManager.class);
            notificationManager.createNotificationChannel(channel);
        }

        Notification notification = new NotificationCompat.Builder(this, "xiaoxulu")
                .build();

        startForeground(DATABASE_QUERY_NOTIFICATION_ID, notification);

        return START_STICKY;
    }



    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
        contentResolver = getContentResolver();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            registerObserver();
        }

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        unregisterObserver();
        stopForeground(true);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    // 注册监听器
    @RequiresApi(api = Build.VERSION_CODES.Q)
    private void registerObserver() {
        observer = new MediaObserver(new Handler());
        contentResolver.registerContentObserver(
                MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL),
                true,
                observer
        );
    }

    // 取消注册监听器
    private void unregisterObserver() {
        if (observer != null) {
            contentResolver.unregisterContentObserver(observer);
        }
    }

    // 自定义的 ContentObserver
    private class MediaObserver extends ContentObserver {
        public MediaObserver(Handler handler) {
            super(handler);
        }

        @SuppressLint("Range")
        @Override
        public void onChange(boolean selfChange, Uri uri) {
            super.onChange(selfChange, uri);
            // 通过 uri 查询 MediaStore 获取文件信息
            // 获取文件路径和名称
            String filePath = "";
            String fileName = "";
            Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                filePath = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DATA));
                fileName = cursor.getString(cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME));
                // 使用 filePath 和 fileName
                Log.d(Constant.TAG, "filePath: " + filePath);
                Log.d(Constant.TAG, "fileName: " + fileName);
                cursor.close();
            }
            // 在这里处理媒体文件变化的逻辑
            // 例如：重新加载文件列表、通知用户等等
            sendMessage(filePath, fileName);
        }

        private void sendMessage(String filePath, String fileName) {
            // 获取通知管理器
            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (notificationManager == null) {
                return;
            }



            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                @SuppressLint("WrongConstant") NotificationChannel mChannel = new NotificationChannel(channel_id, channel_name, importance);
                mChannel.enableLights(true);
                mChannel.enableVibration(true);
                mChannel.setShowBadge(true);
                notificationManager.createNotificationChannel(mChannel);
            }
            // 使用文件路径的哈希值作为通知的唯一标识
            int notificationId = filePath.hashCode();
            // 针对每个下载的文件都发送一个通知
            NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel_id)
                    .setSmallIcon(R.mipmap.icon)
                    .setAutoCancel(true)
                    .setContentTitle(fileName)
                    .setContentText(filePath)
                    .setPriority(importance);


            notificationManager.notify(notificationId, builder.build());

        }



    }
}
